package SysSettingService

import (
	"context"
	"database/sql"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"github.com/gogf/gf/encoding/gjson"
	"time"
)

var cacheTime = time.Duration(3600)
var CachePrefix = "sysConfig:"

func GetConfigModel(ctx context.Context, configKey string) (map[string]interface{}, error) {
	obj := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "sys_config").WherePri(
		"config_key",
		configKey,
	).Cache(cacheTime*time.Second, CachePrefix+configKey)
	res, err := obj.One()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return nil, err
		}
	}
	resMap := res.Map()
	json, err := gjson.DecodeToJson(resMap["config_value"])
	if err != nil {
		return nil, err
	}
	resMap["config_value"] = json
	return resMap, nil
}

func GetConfigDefaultModel(ctx context.Context, configKey string) (*entity.SysConfig, error) {
	var configModel *entity.SysConfig
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "sys_config").WherePri(
		"config_key",
		configKey,
	).Cache(cacheTime*time.Second, CachePrefix+configKey).Scan(&configModel)
	if err != nil {
		return nil, err
	}
	return configModel, nil
}

func GetConfigValueByKey(ctx context.Context, configKey string) (*gjson.Json, error) {
	configModel, err := GetConfigDefaultModel(ctx, configKey)
	if err != nil {
		return &gjson.Json{}, err
	}
	json, err := gjson.LoadContent(configModel.ConfigValue)
	if err != nil {
		return nil, err
	}
	return json, nil
}

func GetConfigValueByKeyName(ctx context.Context, configKey, name string) (interface{}, error) {
	valueByKey, err := GetConfigValueByKey(ctx, configKey)
	if err != nil {
		return nil, err
	}
	value := valueByKey.Get(name)
	return value, nil
}
